package admin

import (
	"example/model"
	"github.com/gin-gonic/gin"
	"math/rand"
	"time"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

var src = rand.NewSource(time.Now().UnixNano())

const (
	// 6 bits to represent a letter index
	letterIdBits = 6
	// All 1-bits as many as letterIdBits
	letterIdMask = 1<<letterIdBits - 1
	letterIdMax  = 63 / letterIdBits
)

func randStr(n int) string {
	b := make([]byte, n)
	// A rand.Int63() generates 63 random bits, enough for letterIdMax letters!
	for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
		if remain == 0 {
			cache, remain = src.Int63(), letterIdMax
		}
		if idx := int(cache & letterIdMask); idx < len(letters) {
			b[i] = letters[idx]
			i--
		}
		cache >>= letterIdBits
		remain--
	}
	return string(b)
}

func Upload(c *gin.Context) {
	dir := "D:/profile/"
	file, e := c.FormFile("file")
	filename := randStr(20) + file.Filename
	if e != nil {
		c.JSON(200, gin.H{"error": e})
	}
	if e := c.SaveUploadedFile(file, dir+filename); e != nil {
		c.JSON(500, gin.H{"message": "文件上传失败"})
	} else {
		c.JSON(200, gin.H{"code": 0, "data": "/manage/profile/" + filename, "message": "success"})
	}
}

func UploadFile(c *gin.Context) {
	var f model.FileModel
	dir := "D:/profile/"
	file, e := c.FormFile("file")
	filename := randStr(20) + file.Filename
	if e != nil {
		c.JSON(200, gin.H{"error": e})
	}
	if e := c.SaveUploadedFile(file, dir+filename); e != nil {
		c.JSON(500, gin.H{"message": "文件上传失败"})
	} else {
		f.Path = "/manage/profile/" + filename
		id := f.Save()
		c.JSON(200, gin.H{"code": 0, "data": id, "message": "success"})
	}
}

func PreView(c *gin.Context) {
	dir := "D:/profile/"
	filename := c.Param("name")
	c.File(dir + filename)
}
